# encoding: utf-8
'''
Created on 2018-8-29
desription:数据库连接助手类
@author: szy
'''

import cx_Oracle
import sys
import time

sys.path.append('./helper')
from helper import InfoMonConstants
#import InfoMonConstants
import threading
from pymongo import MongoClient

class ConnectionHelper:
    conn = None
    _l = None
    def __init__(self,dbName):
        self._l = threading.Lock()
        self.conn = MongoClient("mongodb://{0}:{1}@{2}:{3}/".format(InfoMonConstants.USER, InfoMonConstants.PASSWORD, InfoMonConstants.HOST, InfoMonConstants.PORT))

    def getConnection(self):
        return self.conn

    # def getCursor(self):
    #     return self.conn.cursor()
    def getValue(self, command):
        # self._l.acquire()
        db = self.conn.admin
        # self._l.release()
        return db.command(command)

    def getDatabaseName(self):
        return self.conn.list_database_names()

    def getDbStats(self, dbName, command):
        db = self.conn[dbName]
        return db.command(command)

    def getDataOne(self, dbName, tableName):
        db = self.conn[dbName]
        return db[tableName].find_one()

    def getDiffOptype(self, command, dml_type):
        old_value = self.getValue(command)
        print(old_value['opcounters'])
        time.sleep(1)
        new_value = self.getValue(command)
        return new_value['opcounters'][dml_type] - old_value['opcounters'][dml_type]

    def execute(self, sql):
        cursor = self.conn.cursor()
        cursor.execute(sql)
        return cursor.fetchall()

